package com.lysj.bhp.log.service;


import com.lysj.bhp.log.note.SystemLog;
import com.lysj.bhp.log.domain.TposLog;
import com.lysj.bhp.log.repository.TposLogRepository;
import com.lysj.bhp.log.util.IpUtil;
import com.lysj.bhp.system.base.BaseConst;
import com.lysj.bhp.util.web.Resp;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * Spring AOP实现日志管理
 *
 * @author Exrickx
 */
@Aspect
@Component
@Slf4j
public class SystemLogAspect extends BaseConst {

    private static final ThreadLocal<Date> beginTimeThreadLocal = new NamedThreadLocal<Date>("ThreadLocal beginTime");

    @Autowired(required = false)
    private HttpServletRequest request;
    @Resource
    private TposLogRepository tposLogRepository;

    /**
     * Controller层切点,注解方式
     */
    //@Pointcut("execution(* *..controller..*Controller*.*(..))")
    @Pointcut("@annotation(com.lysj.bhp.log.note.SystemLog)")
    public void controllerAspect() {}

    /**
     * 前置通知 (在方法执行之前返回)用于拦截Controller层记录用户的操作的开始时间
     *
     * @param joinPoint 切点
     * @throws InterruptedException
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws InterruptedException {

        //线程绑定变量（该数据只有当前请求的线程可见）
        Date beginTime = new Date();
        beginTimeThreadLocal.set(beginTime);
    }


    /**
     * 后置通知(在方法执行之后返回) 用于拦截Controller层操作
     *
     * @param joinPoint 切点
     */
    @AfterReturning(returning = "rvt", pointcut = "controllerAspect()")
    public void after(JoinPoint joinPoint, Object rvt) {
        try {
            TposLog tposLog = new TposLog();
            Resp resp = (Resp) rvt;
            if(resp.getCode().equals(Resp.SUCCESS)){
                tposLog.setIsSuccess(Boolean.TRUE);
            }else{
                tposLog.setIsSuccess(Boolean.FALSE);
            }
            //日志标题
            tposLog.setName(getControllerMethodDescription(joinPoint));
            //日志请求url
            tposLog.setRequestUrl(request.getRequestURI());
            //请求方式
            tposLog.setRequestType(request.getMethod());
            //请求参数
            Map<String,String[]> logParams=request.getParameterMap();
            String param = JSONArray.fromObject(logParams).toString();
            if(param != null){
                String params = param.replace("[","").replace("]","");
                tposLog.setRequestParam(params);
            }
            tposLog.setIp(IpUtil.getIpAdrress(request));
            tposLog.setCreateDate(new Date());
            long beginTime = beginTimeThreadLocal.get().getTime();
            long endTime = System.currentTimeMillis();
            //请求耗时
            Long logElapsedTime = endTime - beginTime;
            tposLog.setCostTime(logElapsedTime);
            tposLogRepository.save(tposLog);
        } catch (Exception e) {
            log.error("AOP后置通知异常", e);
        }
    }
    /**
     * @author zwj
     * @date 2018-09-18 11:15
     * @@Description:手动添加日志记录 1.操作名称 2.请求是否成功 3.开始时间
     */
    public void addTposLog(String name,boolean code,Long beginTime) {
        try {
            TposLog tposLog = new TposLog();
            if(code){
                tposLog.setIsSuccess(Boolean.TRUE);
            }else{
                tposLog.setIsSuccess(Boolean.FALSE);
            }
            //日志标题
            tposLog.setName(name);
            //日志请求url
            tposLog.setRequestUrl(request.getRequestURI());
            //请求方式
            tposLog.setRequestType(request.getMethod());
            //请求参数
            Map<String,String[]> logParams=request.getParameterMap();
            String param = JSONArray.fromObject(logParams).toString();
            if(param != null){
                String params = param.replace("[","").replace("]","");
                tposLog.setRequestParam(params);
            }
            tposLog.setIp(IpUtil.getIpAdrress(request));
            tposLog.setCreateDate(new Date());
            long endTime = System.currentTimeMillis();
            //请求耗时
            Long logElapsedTime = endTime - beginTime;
            tposLog.setCostTime(logElapsedTime);
            tposLogRepository.save(tposLog);
        } catch (Exception e) {
            log.error("AOP后置通知异常", e);
        }
    }
    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {

        //获取目标类名
        String targetName = joinPoint.getTarget().getClass().getName();
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取相关参数
        Object[] arguments = joinPoint.getArgs();
        //生成类对象
        Class targetClass = Class.forName(targetName);
        //获取该类中的方法
        Method[] methods = targetClass.getMethods();

        String description = "";

        for (Method method : methods) {
            if (!method.getName().equals(methodName)) {
                continue;
            }
            Class[] clazzs = method.getParameterTypes();
            if (clazzs.length != arguments.length) {
                //比较方法中参数个数与从切点中获取的参数个数是否相同，原因是方法可以重载哦
                continue;
            }
            description = method.getAnnotation(SystemLog.class).description();
        }
        return description;
    }

}
